<?php 

Kurogo::includePackage('Maps');
  
class TravelWebModule extends WebModule 
{ 
    protected $id='travel';
    protected static $defaultModel = 'TravelDataModel';
    protected $feeds = array();

    protected $lat = '';
    protected $lon = '';
    protected $level = 12;
    protected $mapDevice = null;

    protected function initialize() {
        $this->feeds = $this->loadFeedData();
        $this->maxPerPage = $this->getOptionalModuleVar('MAX_RESULTS', 10);
        if (count($this->feeds)==0) {
            return;
        }
    } 

    protected function getDefaultSection() {
        return key($this->feeds);
    }

    protected function getFeed($feed = null) {
        $feed = isset($this->feeds[$feed]) ? $feed : $this->getDefaultSection();
        $feedData = $this->feeds[$feed];
        $feedData['RETRIEVER_CLASS'] = 'TravelDataRetriever';
        if ($feedData['FORMAT'] == 'json') {
            $feedData['PARSER_CLASS'] = 'JSONDataParser';
        } elseif ($feedData['FORMAT'] == 'xml') {
            $feedData['PARSER_CLASS'] = 'XMLDataParser';
        } elseif ($feedData['FORMAT'] == 'csv') {
            $feedData['PARSER_CLASS'] = 'CSVDataParser';
        }
        $modelClass = isset($feedData['MODEL_CLASS']) ? $feedData['MODEL_CLASS'] : self::$defaultModel;
        $controller = DataModel::factory($modelClass, $feedData);
        return $controller;
    }

    private function getMapDevice()
    {
        if (!$this->mapDevice) {
            $this->mapDevice = new MapDevice($this->pagetype, $this->platform);
        }
        return $this->mapDevice;
    }

    private function getImageController()
    {
        return MapImageController::factory(
            array('JS_MAP_CLASS' => 'GoogleJSMap', 'center' => $this->lat . ',' . $this->lon, 'DEFAULT_ZOOM_LEVEL' => $this->level),
            $this->getMapDevice());
    }

    protected function initializeDynamicMap($feature)
    {
        // set up base map
        $baseMap = $this->getImageController();
        $baseMap->setWebModule($this);

        // add data
        foreach ($this->getSelectedPlacemarks($feature['placemarks']) as $aPlacemark) {
            $baseMap->addPlacemark($aPlacemark);
        }

        // code for embedding base map
        $baseMap->setMapElement('mapimage');
        $baseMap->prepareForOutput();
        foreach ($baseMap->getIncludeScripts() as $includeScript) {
            $this->addExternalJavascript($includeScript);
        }
        foreach ($baseMap->getInternalScripts() as $includeScript) {
            $this->addInternalJavascript($includeScript);
        }

        $latRange = $baseMap->getMinimumLatSpan();
        $lonRange = $baseMap->getMinimumLonSpan();
        $this->addInlineJavascriptFooter(
            //"var COOKIE_PATH = '".COOKIE_PATH."';\n".
            //"var BOOKMARK_LIFESPAN = ".$this->getBookmarkLifespan().";\n".
            "var CONFIG_MODULE = '{$this->configModule}';\n".
            "var MIN_LAT_SPAN = {$latRange};\n".
            "var MIN_LON_SPAN = {$lonRange};\n".
            'var NO_RESULTS_FOUND = "'.$this->getLocalizedString('NO_RESULTS').'";');
        $this->addInlineJavascriptFooter($baseMap->getFooterScript());

        if ($this->page != 'pane') {
            $this->addOnLoad('addClass(document.body, "fullscreen");');
        }
        $this->addOnOrientationChange('updateContainerDimensions();');
    }

    protected function getSelectedPlacemarks($placemarks = array())
    {
        $selectedPlacemarks = array();
        foreach ($placemarks as $placemark) {
            $lat = $placemark['lat'];
            $lon = $placemark['lon'];

            $title = $placemark['title'];
            if (!$title) {
                $title = "$lat,$lon";
            }
            $selectedPlacemark = new BasePlacemark(
                new MapBasePoint(array(
                    'lat' => $lat,
                    'lon' => $lon,
                    )));
            $selectedPlacemark->setTitle($title);

            $selectedPlacemarks[] = $selectedPlacemark;
        }

        return $selectedPlacemarks;
    }

    protected function generateTabForKey($tabKey, $feature, &$tabJavascripts) {
        switch ($tabKey) {
            case 'map': {
                    if (count($feature['placemarks'])) {
                        $this->initializeDynamicMap($feature);
                        $tabJavascripts[$tabKey] = "map.setCenter(new google.maps.LatLng('$this->lat', '$this->lon'))";
                        return true;
                    } else
                        return false;
                }
            case 'info': {
                    return true;
                }
            case 'photo': {
                    if (count($feature['photos']))
                        return true;
                    else
                        return false;
                }
        }
    }

    public function linkForItem(KurogoObject $mapItem, $options=null)
    {
    }

    protected function initializeForPage() { 

        if (count($this->feeds) == 0) {
            throw new KurogoConfigurationException($this->getLocalizedString('TRAVEL_FEED_CONFIGURE_ERROR_MESSAGE'));
        }

        switch ($this->page) 
        { 
            case 'index': 
                foreach($this->feeds as $feed => $feedData){
                    $list['title'] = $feedData['TITLE'];
                    $list['url'] = $this->buildBreadcrumbURL('list', array('id' => $feed), true);
                    $listArr[] = $list;
                }
                $this->assign('listArr', $listArr);
                break;
                
            case 'list':
                $id = $this->getArg(array('id'), null);
                $format = $this->feeds[$id]['FORMAT'];
                $title = $this->feeds[$id]['TITLE'];
                $controller = $this->getFeed($id);
                $name = $this->feeds[$id]['NAME'];
                $start = $this->getArg('start', 0);
                $controller->setStart($start);
                $controller->setLimit($this->maxPerPage);

                foreach ($controller->items() as $i => $test) {
                    $list['title'] = $test[$name];
                    $list['url'] = $this->buildBreadcrumbURL('detail', array('msg' => $id, 'id' => $start + $i), true);
                    $listArr[] = $list;
                }

                $totalItems = $controller->getTotalItems();
                $previousURL = null;
                $nextURL = null;

                if ($totalItems > $this->maxPerPage) {
                    $args = $this->args;
                    if ($start > 0) {
                        $args['start'] = $start - $this->maxPerPage;
                        $previousURL = $this->buildBreadcrumbURL($this->page, $args, false);
                    }

                    if (($totalItems - $start) > $this->maxPerPage) {
                        $args['start'] = $start + $this->maxPerPage;
                        $nextURL = $this->buildBreadcrumbURL($this->page, $args, false);
                    }
                }

                $this->assign('maxPerPage',     $this->maxPerPage);
                $this->assign('previousURL',    $previousURL);
                $this->assign('nextURL',        $nextURL);
                $this->assign('listArr', $listArr);
                $this->assign('title', $title);
                break;

            case 'detail':
                $id = $this->getArg(array('id'), null);
                $msg = $this->getArg(array('msg'), null);
                $field = $this->feeds[$msg]['FIELD'];
                $name = $this->feeds[$msg]['NAME'];
                $arrFields = explode(",", $field);
                $controller = $this->getFeed($msg);  	 
                $details = $controller->getDetail($id);

                $feature = array('placemarks' => array(), 'photos' => array());

                if (isset($this->feeds[$msg]['PIC_FIELD'])) {
                    $pic = $this->feeds[$msg]['PIC_FIELD'];
                    $picFields = explode(",", $pic);
                    foreach ($picFields as $picField) {
                        $picArrs = explode(":", $picField);
                        if (!empty($details[$picArrs[0]])) {
                            $picArr = array($details[$picArrs[0]],$details[$picArrs[1]]);
                            $feature['photos'][] = $picArr;
                        }
                    }
                    $this->assign('photos', $feature['photos']);
                }
                if (isset($this->feeds[$msg]['MAP_FIELD'])) {
                    $map = $this->feeds[$msg]['MAP_FIELD'];
                    list($lonField, $latField) = explode(",", $map);

                    $lat = $details[$latField];
                    $lon = $details[$lonField];

                    $this->lat = $lat;
                    $this->lon = $lon;

                    $feature['placemarks'][] = array('lat' => $lat, 'lon' => $lon, 'title' => $details[$name]);
                }
                foreach ($arrFields as $arrField) {
                    $fields = explode(":", $arrField);
                    if (isset($fields[1])) {
                        $key[$fields[0]] = array($details[$fields[0]], $fields[1]);
                    } else {
                        $key[$fields[0]] = array($details[$fields[0]], '');
                    }
                }
                $this->assign('name', $key[$name][0]);
                $this->assign('keys', $key);

                $detailConfig = $this->loadPageConfigArea('detail');
                $tabKeys = array();
                $tabJavascripts = array();
                $possibleTabs = $detailConfig['tabs']['tabkeys'];
                foreach ($possibleTabs as $tabKey) {
                    if ($this->generateTabForKey($tabKey, $feature, $tabJavascripts)) {
                        $tabKeys[] = $tabKey;
                    }
                }
                $this->assign('tabKeys', $tabKeys);
                $this->enableTabs($tabKeys, null, $tabJavascripts);
                break;
         } 
     } 
 }
